package com.atguigu.day05;

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.util.Collector;

public class Example8 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 数据流中有5个事件：
        // Watermark(Long.MIN_VALUE)
        // Watermark(-200s)
        // "a" 1000L
        // Watermark(200s)
        // Watermark(Long.MAX_VALUE)
        env
                .addSource(new SourceFunction<String>() {
                    @Override
                    public void run(SourceContext<String> ctx) throws Exception {
                        ctx.emitWatermark(new Watermark(-200 * 1000L));
                        // 第一个参数：将要发送的数据
                        // 第二个参数：将要发送的数据的事件时间
                        ctx.collectWithTimestamp("a", 1000L);
                        ctx.emitWatermark(new Watermark(200 * 1000L));
                    }

                    @Override
                    public void cancel() {

                    }
                })
                .keyBy(r -> r)
                .process(new KeyedProcessFunction<String, String, String>() {
                    @Override
                    public void processElement(String in, Context ctx, Collector<String> out) throws Exception {
                        // ctx.timestamp()获取输入数据in的事件时间
                        ctx.timerService().registerEventTimeTimer(ctx.timestamp() + 100 * 1000L);

                        out.collect("输入数据：" + in + "，当前process算子的手表是：" + ctx.timerService().currentWatermark() + "，注册了一个定时器：" +
                                "" + (ctx.timestamp() + 100 * 1000L));
                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        out.collect("定时器：" + timestamp + "触发了，当前process算子的手表是：" + ctx.timerService().currentWatermark());
                    }
                })
                .print();

        env.execute();
    }
}
